package com.qf.hw.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class MapperUtils {

    /**
     * 线程本地对象---线程域对象--实现同一个线程中，不同方法间的对象传递
     *      现在我定义的这个线程域对象就是用来传递SqlSession对象的
     */
    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    /**
     * 静态成员随着类的初始化而初始化，类只会初始化一次
     */
    private static SqlSessionFactory factory;

    static {
        try {
            factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static<T> T getMapper(Class<T> cls){
        SqlSession sqlSession = factory.openSession(true);

        //将sqlsession对象存入ThreadLocal中
        tl.set(sqlSession);

        T mapper = sqlSession.getMapper(cls);

        return mapper;
    }

    public static void close(){

        //从ThreadLocal中获取当前线程保存的sqlsession对象
        SqlSession sqlSession = tl.get();
        if (sqlSession != null){
            sqlSession.close();

            //一定要将其从ThreadLocal中移除，防止内存泄露
            tl.remove();
        }

    }
}
